package cn.owng.cli;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.text.StringSubstitutor;

import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Setter
@Getter
@Accessors(chain = true)
public class Env {

    @Setter
    @Getter
    @Accessors(chain = true)
    public static class Db {
        private String url;
        private String database;
        private String query;
        private String username;
        private String password;
    }

    private static final Env env = new Env();

    private Db db;

    private Properties properties;


    private Env() {

    }

    public static Env get() {
        return env;
    }

    public static Db db() {
        return env.getDb();
    }

    static void setup(String content) {
        StringSubstitutor sub = new StringSubstitutor(System.getenv());
        sub.setValueDelimiter(":");
        try (StringReader reader = new StringReader(sub.replace(content))) {
            Properties prop = new Properties();
            prop.load(reader);
            env.setProperties(prop);
            env.setDb(new Db()
                    .setUrl(prop.getProperty("db.url"))
                    .setDatabase(prop.getProperty("db.database"))
                    .setQuery(prop.getProperty("db.query"))
                    .setUsername(prop.getProperty("db.username"))
                    .setPassword(prop.getProperty("db.password")));
        } catch (IOException e) {
            throw new RuntimeException("error parsing properties", e);
        }
    }
}
